import cgi
import json
import webapp2
import datetime

from google.appengine.ext import ndb
import model_child

class Att (ndb.Model):
    """ Models an individual attendance entry with content and id (child id and date)"""

    child_id =     ndb.StringProperty()
    date =      ndb.DateProperty()
    is_arrived =        ndb.BooleanProperty()
    child_id_and_date = ndb.StringProperty()

    @staticmethod
    def update_att_by_id_and_date_from_json(data_json):
        """ create (or update) child_id attendance by date """
        data = json.loads(data_json)
        curr_date = datetime.date.today()
        unique_id = data.get("child_id") + str(curr_date)
        att = Att(child_id =        data.get("child_id"),
                  date =            curr_date,
                  is_arrived =      data.get("is_arrived"),
                  child_id_and_date= unique_id)
        check_att_exists = Att.query(Att.child_id_and_date == unique_id).get()
        if check_att_exists != None:
            ndb.Key(Att, int(check_att_exists.key.id())).delete()
        att.put()

    @staticmethod
    def get_att_of_child_by_child_id_and_date(data_json):
        """ return attendance of a child by his id and date """
        data = json.loads(data_json)
        child_id_given = data.get('child_id')
        date_given = str(data.get('date'))
        unique_id = child_id_given + date_given
        check_att_exists = Att.query(Att.child_id_and_date == unique_id).get()
        if check_att_exists == None:
            return -1
        else:
            if check_att_exists.is_arrived == True:
                return 1
            else:
                return -1

    @staticmethod
    def get_att_report_by_month(data_json):
        """ return a list with all att of children for month given """
        data = json.loads(data_json)
        given_month = data.get("month")
        given_child_id = data.get("child_id")
        atts = ndb.gql("SELECT * FROM Att WHERE child_id = :c_id  ORDER BY date", c_id=given_child_id)
        curr_date = datetime.date.today()
        year = curr_date.year
        if given_month == 2:
            if(year % 4 == 0 and year % 100) or year % 400 == 0:
                days = 29
            else:
                days=28
        elif given_month == 4 or given_month == 6 or given_month == 9 or given_month == 11:
            days = 30
        else:
            days = 31
        res = [ 0 for i in range(days+1) ]
        flag = True
        child_info_json = model_child.Child.get_child_info(given_child_id)
        child_info = json.loads(child_info_json)
        d = {"child_id": given_child_id, "first_name": child_info.get("first_name"), "last_name": child_info.get("last_name")}
        res[0] = json.dumps(d)
        for a in atts:
            if str(a.date.month) == str(given_month):
                res[a.date.day] = a.is_arrived
                flag = False
        if flag:
            return -1
        return res

    @staticmethod
    def get_missing_childs_over_2_days(data_json):
        """ return a list with all children who missing 2 days in a row or above """
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        children_in_KG = model_child.Child.get_children_in_KG_id(given_KG_id)
        res = []
        children_in_KG.reverse()
        # return children_in_KG
        for child_id in children_in_KG:
            curr_date = datetime.date.today()
            child_info_json = model_child.Child.get_child_info(child_id)
            child_info = json.loads(child_info_json)
            count = 0
            d = {"child_id": str(child_id), "date": str(curr_date)}
            while (Att.get_att_of_child_by_child_id_and_date(json.dumps(d)) != 1) or count > 30:
                count+=1
                curr_date = curr_date - datetime.timedelta(days=1)
                d = {"child_id": str(child_id), "date": str(curr_date)}
            if count > 1:
                data = {"child_id": str(child_id), "days": count, "first_name": child_info.get("first_name"), "last_name": child_info.get("last_name")}
                data_json = json.dumps(data)
                res.append(data_json)
        return res
